package t211124;

import java.util.Arrays;

/**
 * @Author: DengJia
 * @Date: 2021/11/24 20:42
 * @Description:
 */
class Shared {
    private int refCount = 0;
    private static long counter = 0;
    private final long id = counter++;

    public Shared() {
        System.out.println("创建：" + this);
    }

    public void addRef() {
        this.refCount++;
    }

    protected void dispose() {
        if (--refCount == 0) {
            System.out.println("清除：" + this);
        }
    }

    @Override
    public String toString() {
        return "Shared " + this.id;
    }
}

class Composing {
    private final Shared shared;
    private static long counter = 0;
    private final long id = counter++;

    public Composing(Shared shared) {
        System.out.println("创建：" + this);
        this.shared = shared;
        this.shared.addRef();
    }

    protected void dispose() {
        System.out.println("清除：" + this);
        this.shared.dispose();
    }

    @Override
    public String toString() {
        return "Composing " + id;
    }
}

public class ReferenceCounting {
    public static void main(String[] args) {
        Shared shared = new Shared();
        Composing[] composing = {
                new Composing(shared), new Composing(shared), new Composing(shared), new Composing(shared), new Composing(shared)
        };

        Arrays.stream(composing).forEach(Composing::dispose);
    }
}
